物件導向的基礎範例


Posted by YongChenSu on 2020-12-09

當在 call 物件實例時,就是在 call constructor()

  • constructor 建構子,適合將狀態初始化
  • 在物件導向裡面用 this 的情形,誰呼叫它誰就是 this,以以下例子來說,要對 d 做 setName,故 this 就是 d。
class Dog {
  // setName(name) {
    // this.name = name
  // }
  constructor(name) {
    this.name = name
  }
  getName() {
    return this.name
  }
  sayHello() {
    console.log(this.name)
  }
}

var d = new Dog('abc')
// d.setName('777')
d.sayHello()

var b = new Dog('456')
b.sayHello()


參考資源


#程式導師實驗計畫第四期 #前端 #object oriented







Related Posts

{210410} 命令行上的集特盒

{210410} 命令行上的集特盒

 JS30 Day 3 筆記

JS30 Day 3 筆記

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段三:個人專案前準備~Dive into topics)

AppWorks School Batch #16 Front-End Class 學習筆記&心得(駐點階段三:個人專案前準備~Dive into topics)


Comments